import { generateTaskId, recordMaterialMetrics4PC, submitImgOptimizeTask4PC, queryImgOptimizeTask4PC } from '@Api/doudianTools/aiApi'
import { get_lid } from "@Utils/getPageDecrypt"
import { store } from "~store"
import { Modal } from '@bytedance/mona-ui';

let putGeneratedAiImages = []
// {
//     product_id,
//     url,
//     status: 0, // 未开始 1进行中 2已完成 3部分完成 4失败
//     put_urls: [],
//     error: '',
//     stop: false, // 是否手动停止
// }

const pushObjctInfo = {
    status: 0, // 未开始 1进行中 2已完成 3部分完成 4失败
    put_urls: [],
    error: '',
    stop: false, // 是否手动停止
}
const gereterConfig = {
    out_time: 60 * 1000, // 超时时间
    run_limit: 5, // 并行任务数量
    retry: 3, // 重试次数
}
let showConter = false
export const generatedAiInit = (data) => {
    // i = i + 1
    // console.log(i)
    if (!data) return

    // if (!data.url) throw new Error('缺少参数')
    putGeneratedAiImages.push(Object.assign({}, pushObjctInfo, data))
    // runGetAiImageFunc(data)
    data.run_out_time = 80 * 1000
    data.get_image_time = 2000
    const aiClassObj = new GeneratedAiImages(data)
    // console.log('aiClassObj', aiClassObj)
    return aiClassObj
    // putGeneratedAiImages.push(data)
    // console.log('gereterConfig', gereterConfig)
    // console.log('putGeneratedAiImages', putGeneratedAiImages)
}

class GeneratedAiImages {
    constructor(option) {
        const { __token } = store.getState().jinritemaiDecrypt
        this.__token = __token
        this.data = option
        this.url = option.url
        this.get_image_time = option.get_image_time || 2000 // 默认轮巡的时间
        this.run_out_time = option.run_out_time || 120 * 1000 // 默认超时不出的时间
        this.trace_id = ''
        this.cheackInfoAiData = {}
        this.upInfoDataRunter = {}
        this.runstatusInfos = null
        this.getrunstatusDataFindInfos = null
        this.run_state_time = 0
        this.optimize_strategy_extra = option.optimize_strategy_extra || {}
        this.run_end_images = []
        this.optimize_strategy = option.optimize_strategy
        this.run_end_image_obj = []

        this.optimized_video_infos = []

        this.run_status = 0 // 0 未开始 1进行中 2已完成 3部分完成 4失败
        this.setGetAiImageLodinStatus = option.setGetAiImageLodinStatus || null
        this.cb = option.cb || null
        this.stopRun = option.stopRun || null
        this.img_format = option.img_format || 1
        this.run_err_text = ''

        this.errormsg = ''
        if (!this.stopRun) {
            this.run()
        }
    }

    async run(url = this.url, config) {
        this.url = url || this.url
        this.run_status = 0
        this.setGetAiImageLodinStatus && this.setGetAiImageLodinStatus(true)
        const getTraceId = await generateTaskId()
        // console.log('getTraceId', getTraceId)
        if (!getTraceId.code) {
            this.trace_id = getTraceId.data.trace_id
            this.cheackForApi(config)
            return
        }
        // console.log('接口错误，没有数据')
    }
    async cheackForApi(config) {
        this.cheackInfoAiData = {
            "record_material_metrics": [
                {
                    "trace_id": this.trace_id,
                    "event_type": "submit",
                    "material_tracking_info": {
                        "material_type": 29,
                        "product_id": this.data.product_id || '',
                        "origin_material_url": this.url,
                        "scale": 1
                    },
                    "action_tracking_info": {
                        "app_source": "pc",
                        "operate_entrance": "/ffa/creative/tools",
                        "is_batch_create": false,
                        "generate_first_type": "智能做图",
                        "apply_scenes": "主图1:1",
                        "generate_second_type": config?.optimize_strategy || "一键成图",
                        "material_scenes": config?.extra_map || "{\"img_format\":1}"
                    }
                }
            ],
            "appid": 1,
            "__token": this.__token,
            "_bid": "ffa_material",
            "_lid": get_lid()
        }
        const getDters = await recordMaterialMetrics4PC(this.cheackInfoAiData)
        this.run_status = 1
        // console.log('上传前的检查', getDters)
        if (this.cheackStopRun(getDters)) return
        // if (getDters.code == 10001) {
        //     const _this = this
        //     _this.run_status = 5
        //     _this.run_err_text = getDters.msg
        //     return Modal.warning({
        //         title: '提示',
        //         content: getDters.msg,
        //         onOk() {
        //             console.log('OK');
        //             _this.cb(_this)
        //             _this.setGetAiImageLodinStatus && _this.setGetAiImageLodinStatus(false)
        //         },
        //         onCancel() {
        //             console.log('Cancel');
        //             _this.cb(_this)
        //             _this.setGetAiImageLodinStatus && _this.setGetAiImageLodinStatus(false)
        //         },
        //     })
        // }
        if (getDters.code === 0 && getDters.data && getDters.data.result === "success") {
            // console.log('任务创建成功 可以开始')
            this.putrunStitertus(config)
            return
        }
        // console.log('创建失败 返回结果 或者重试')


    }
    async putrunStitertus(config) {
        this.upInfoDataRunter = {
            "product_id": this.data.product_id,
            "img": this.url,
            "optimize_strategy": config?.optimize_strategy || "作图工具一键成图ForPc",
            "img_format": this.img_format,
            "optimize_strategy_extra": config?.optimize_strategy_extra || {},
            "appid": 1,
            "__token": this.__token,
            "_bid": "ffa_material",
            "_lid": get_lid()
        }
        const getrunStatus = await submitImgOptimizeTask4PC(this.upInfoDataRunter)
        if (!getrunStatus.code) {
            // console.log('任务提交成功')
            this.runstatusInfos = getrunStatus.data
            this.run_state_time = Date.now()
            this.runGetAiResuster()
            return
        }
        if (this.cheackStopRun(getrunStatus)) return
        setTimeout(() => {
            // console.log('延时重新提交')
            this.run()
        }, 5000)
        // console.log('任务提交失败 重试 或者如何')

    }
    cheackStopRun(getrunStatus) {
        if (getrunStatus.code == 10001) {
            const _this = this
            _this.run_status = 5
            _this.run_err_text = getrunStatus.msg
            if (showConter) {
                _this.cb(_this)
                _this.setGetAiImageLodinStatus && _this.setGetAiImageLodinStatus(false)
                return true
            }
            showConter = true
            Modal.warning({
                title: '提示',
                content: getrunStatus.msg,
                onOk() {
                    showConter = false
                    // console.log('OK');
                    _this.cb(_this)
                    _this.setGetAiImageLodinStatus && _this.setGetAiImageLodinStatus(false)
                },
                onCancel() {
                    showConter = false
                    // console.log('Cancel');
                    _this.cb(_this)
                    _this.setGetAiImageLodinStatus && _this.setGetAiImageLodinStatus(false)
                },
            })
            return true
        }
        return false
    }
    runGetAiResuster() {
        setTimeout(() => {
            this.getRunstatusTimeOut()
        }, this.get_image_time)
    }
    async getRunstatusTimeOut() {
        // console.log('runstatusInfos', this.runstatusInfos)
        if (!this.runstatusInfos) {
            return console.log('任务没有提交 不算成功 不可查询')
        }
        this.getrunstatusDataFindInfos = {
            task_id: this.runstatusInfos.task_id,
            app_id: this.runstatusInfos.app_id,
            tool_source: this.runstatusInfos.tool_source,
            optimize_strategy: this.upInfoDataRunter.optimize_strategy,
            appid: 1,
        }

        const getStatus = await queryImgOptimizeTask4PC(this.getrunstatusDataFindInfos)
        // console.log('getStatus+++', getStatus)
        if (!getStatus.code) {
            this.continueOrStop(getStatus.data)
        } else {
            // console.log('接口错误，没有数据 重新查询 直到超时')
            this.continueOrStop(getStatus.data)
        }

    }
    continueOrStop(data) {
        const { status, img_list, optimized_img_infos, optimized_video_infos, msg } = data


        this.run_end_images.push(...img_list)
        this.run_end_image_obj.push(...optimized_img_infos)
        // this.run_end_images = img_list过滤去重
        this.run_end_images = [...new Set(this.run_end_images)]
        this.run_end_image_obj = this.myseta(this.run_end_image_obj) //[...new Set(this.run_end_image_obj)]
        // console.log('this.run_end_images', this.run_end_images)

        this.optimized_video_infos = optimized_video_infos
        if (img_list && img_list.length > 0) {
            this.run_status = 4
            this.cb && this.cb(this)
            this.setGetAiImageLodinStatus && this.setGetAiImageLodinStatus(false)
        }
        if (status === '执行成功') {
            // console.log('任务执行成功', this.run_end_images)
            this.run_status = 2
            this.cb && this.cb(this)
            this.setGetAiImageLodinStatus && this.setGetAiImageLodinStatus(false)

            return
        }
        const nowTime = Date.now()
        if (status === '执行失败' || (nowTime - this.run_state_time > this.run_out_time)) {
            // console.log('任务执行超时, 停止执行 返回任务结果', this.run_end_images)
            this.run_status = 3
            this.errormsg = msg
            this.cb && this.cb(this)
            this.setGetAiImageLodinStatus && this.setGetAiImageLodinStatus(false)
            return
        }
        this.runGetAiResuster()
    }
    myseta(ary) {
        const strings = ary.map((item) => JSON.stringify(item))
        // 使用Set数据结构去重对象
        // return new Set(strings)

        // 使用Array.from()把Set数据结构去重对象后的结构，转为数组
        // return Array.from(new Set(strings))

        // 使用Array.from()转为数组，然后再使用数组的map方法把数组里面的字符串类型转化为对象类型:
        return Array.from(new Set(strings)).map((item) => JSON.parse(item))

    }
    runMaidian(url, optimize_strategy_extra, extra_map) {
        // console.log('runMaidian')
        this.run(url, {
            optimize_strategy: 'AI卖点图',
            optimize_strategy_extra,
            extra_map: extra_map && JSON.stringify(extra_map)
        })
        return '进行中'
    }
    async runOpenVideo(optimize_strategy_extra) {
        this.upInfoDataRunter = {
            // "product_id": this.data.product_id,
            // "img": this.url,
            "optimize_strategy": this.optimize_strategy || "视频一键生成",
            "img_format": this.img_format,
            "optimize_strategy_extra": optimize_strategy_extra,
            "appid": 1,
            "__token": this.__token,
            "_bid": "ffa_material",
            "_lid": get_lid()
        }
        const getrunStatus = await submitImgOptimizeTask4PC(this.upInfoDataRunter)
        console.log('getrunStatus', getrunStatus)
        if (!getrunStatus.code) {
            // console.log('任务提交成功')
            this.runstatusInfos = getrunStatus.data
            this.run_state_time = Date.now()
            this.runGetAiResuster()
            return
        }
        if (this.cheackStopRun(getrunStatus)) return
        setTimeout(() => {
            // console.log('延时重新提交')
            this.runOpenVideo()
        }, 5000)
    }

}


export const runGetAiImageFunc = async (data) => {
    if (!data) return

    if (!data.product_id || !data.url) return
    // console.log('runGetAiImageFunc', data)
    // 获取任务id trace_id
    const getTraceId = await generateTaskId()
    // console.log('getTraceId', getTraceId)
    let trace_id
    if (!getTraceId.code) {
        trace_id = getTraceId.data.trace_id
    }
    upTraceCheack()
}

function formaterData(data) {

}

export const upTraceCheack = async (data) => {
    const cheackData = formaterData(data)
}